package com.market.inteceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.market.common.Constants;
import com.market.model.Manager;

public class LoginInteceptor implements HandlerInterceptor {

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object o) throws Exception {
		Manager manager = (Manager)request.getSession().getAttribute(Constants.SESSION_USER);
	
	   if(manager != null && StringUtils.isNoneBlank(manager.getUserCode())){
			return true;
		}
		
		response.sendRedirect("/login");
		return false;
	}

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}
	private void sendRedirect(String sendUrl,HttpServletRequest request,HttpServletResponse response) throws Exception{
		StringBuffer sb = request.getRequestURL();
		if(StringUtils.isNotEmpty(request.getQueryString()))
			sb.append("?").append(request.getQueryString());
		response.sendRedirect(sendUrl + (sendUrl.contains("?") ? "&" : "?")
				+"ref="+ URLEncoder.encode(sb.toString(), "utf-8"));
	}
}
